<script setup lang="ts">
import "@/assets/css/styles.css";
import { getApplicationInfo, getParameters } from "@/api/dify";
import { onMounted, ref } from "vue";
import router from "@/router";

// 用户信息
const userData = {
  id: 3,
  password: "123456",
  realName: "youyou",
  email: "123456@163.com",
  roles: ["user"],
  username: "youyou",
  icon: "/public/favicon.ico",
  difyTab: [
    {
      dify: "珠宝行业资讯-店长老板通用版1.0",
      apiKey: "app-QJIJ4EEoOzuyCTxgcVxD7GWE",
      desc: "",
      icon: ""
    },
    {
      dify: "珠宝门店智能顾问--元元",
      apiKey: "app-ZlIIGv3jIZkqKJKtscpEYO2X",
      desc: "",
      icon: ""
    },
    {
      dify: "超级AI",
      apiKey: "app-yNIdZDVzTn8CO4ujIcTQodK1",
      desc: "",
      icon: ""
    },
    {
      dify: "珠宝门店高毛利产品助理",
      apiKey: "app-5YiLhQuo76Zkf0kq0LYYx2CQ",
      icon: ""
    }
  ]
};

const isLoading = ref(true); // 用于控制加载状态
// 存储每个应用的信息
const applicationInfo = ref<any[]>([]);

// 获取应用信息并更新页面数据
const fetchApplications = async () => {
  try {
    isLoading.value = true; // **开始加载**
    // 使用 Promise.all 来并行请求所有应用数据
    const promises = userData.difyTab.map(tab => {
      return getApplicationInfo(tab.apiKey).then(data => {
        // 将 apiKey 和返回的数据合并
        return { ...data, apiKey: tab.apiKey };
      });
    });
    // 等待所有请求完成
    // 把结果存储到 applicationInfo 中
    applicationInfo.value = await Promise.all(promises);
    isLoading.value = false; // **加载完成**
  } catch (error) {
    console.error("加载应用信息失败:", error);
  }
};

// 获取应用参数信息
const handleClick = async (apiKey: string) => {
  try {
    isLoading.value = true; // 请求开始时显示加载状态
    const response = await getParameters(apiKey); // 通过传递 apiKey 调用 getParameters 函数
    // 将 apiKey 添加到返回的 response 中
    const updatedResponse = {
      ...response, // 保留原有的 response 数据
      apiKey: apiKey // 添加 apiKey
    };
    isLoading.value = false;
    // 将 应用参数信息和 apiKey 转化为 JSON 字符串 存储到 localStorage
    localStorage.setItem("parameters", JSON.stringify(updatedResponse));
    await router.push({ name: "DifyChat" });
  } catch (error) {
    console.error("请求参数失败:", error);
    isLoading.value = false;
  }
};

// 页面加载时调用 fetchApplications 获取数据
onMounted(() => {
  fetchApplications();
});
</script>

<template>
  <div class="page-container">
    <div class="button-group" style="height: calc(100vh - 110px)">
      <van-cell
        v-for="(appInfo, index) in applicationInfo"
        :key="index"
        is-link
        icon="apps-o"
        :title="appInfo.name"
        :value="appInfo.tags[0]"
        :label="appInfo.description"
        @click="handleClick(appInfo.apiKey)"
      >
      </van-cell>
    </div>

    <!-- 如果没有应用信息，显示提示 -->
    <div
      v-if="!isLoading && applicationInfo.length === 0"
      class="my-empty-state"
    >
      <p>什么也没有^O^</p>
    </div>

    <!-- 加载中状态 -->
    <div v-if="isLoading" class="my-loading-container">
      <van-loading color="#1989fa" />
    </div>
  </div>
</template>
